/*
 * @author Chris
 * @since 2023/2/7 11:20
 *
 * @brief    The project will ...
 *
 * @note     ...
 *
 * @warning  Do not to ...
 *
 * Change Logs:
 *   Date           Author       Notes
 *   2023/2/7     Chris        the first version
 */

#include "8052.h"
#include "stdio.h"
#include "string.h"

__bit flag300ms = 1;
unsigned char T0RH = 0;
unsigned char T0RL = 0;

void ConfigTimer0(unsigned int ms);

unsigned char GetADCValue(unsigned char channel);

void ValueToString(unsigned char *str, unsigned char val);

extern void InitLcd1602();

extern void Lcd1602Show(unsigned char x, unsigned char y, unsigned char *buf, unsigned char len);

extern void I2CStart();

extern __bit I2CWrite(unsigned char dat);

extern unsigned char I2CReadAck();

extern unsigned char I2CReadNak();

extern void I2CStop();

int main() {
    EA = 1;
    ConfigTimer0(10);
    InitLcd1602();
    Lcd1602Show(0, 0, "AIN0  AIN1  AIN3", strlen("AIN0  AIN1  AIN3"));

    while (1) {
        if (flag300ms) {
            flag300ms = 0;

            unsigned char val;
            unsigned char str[10];
            //显示通道 0 的电压
            val = GetADCValue(0); //获取 ADC 通道 0 的转换值
            ValueToString(str, val); //转为字符串格式的电压值
            Lcd1602Show(0, 1, str, strlen(str)); //显示到液晶上
            //显示通道 1 的电压
            val = GetADCValue(1);
            ValueToString(str, val);
            Lcd1602Show(6, 1, str, strlen(str));
            //显示通道 3 的电压
            val = GetADCValue(3);
            ValueToString(str, val);
            Lcd1602Show(12, 1, str, strlen(str));
        }
    }

}

void ValueToString(unsigned char *str, unsigned char val) {
    //电压值=转换结果*2.5V/255，式中的 25 隐含了一位十进制小数
    val = (val * 25) / 255;
    str[0] = (val / 10) + '0'; //整数位字符
    str[1] = '.'; //小数点
    str[2] = (val % 10) + '0'; //小数位字符
    str[3] = 'V'; //电压单位
    str[4] = '\0'; //结束符
}

unsigned char GetADCValue(unsigned char channel) {
    I2CStart();
    if (!I2CWrite(0x48 << 1)) {
        I2CStop();
        return 0;
    }
    I2CWrite(0x40 | channel);

    I2CStart();
    I2CWrite((0x48 << 1) | 1);
    I2CReadAck();
    unsigned char val = I2CReadNak();
    I2CStop();

    return val;
}

void ConfigTimer0(unsigned int ms) {
    unsigned char tmp = 65536 - 11059200 * ms / 12 / 1000 + 12;
    T0RH = tmp >> 8;
    T0RL = tmp & 0xFF;
    TH0 = T0RH;
    TL0 = T0RL;
    TMOD = (TMOD & 0xF0) | 0x01;

    ET0 = 1;
    TR0 = 1;
}

/**
 * 定时器 T0 中断服务函数
 */
void InterruptTimer0() __interrupt(1) {
    TH0 = T0RH;
    TL0 = T0RL;
    static unsigned char cnt = 0;

    if (cnt++ >= 30) {
        cnt = 0;
        flag300ms = 1;
    }
}
